<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.0.1">


  <link rel="mask-icon" href="/images/logo.svg?v=7.0.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.0.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="概要 前面一节，通过简单配置即可实现SpringSecurity表单认证功能，而今天这一节将通过阅读源码的形式来学习SpringSecurity是如何实现这些功能, 前方高能预警，本篇分析源码篇幅较长。">
<meta name="keywords" content="SpringBoot,SpringSecurity">
<meta property="og:type" content="article">
<meta property="og:title" content="【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读">
<meta property="og:url" content="http://www.yukonga.cn/2019/04/12/【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读/index.html">
<meta property="og:site_name" content="yukong&#39;s blog">
<meta property="og:description" content="概要 前面一节，通过简单配置即可实现SpringSecurity表单认证功能，而今天这一节将通过阅读源码的形式来学习SpringSecurity是如何实现这些功能, 前方高能预警，本篇分析源码篇幅较长。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://i.loli.net/2019/05/24/5ce7b959b91be68275.png">
<meta property="og:image" content="https://i.loli.net/2019/05/24/5ce7b959b91be68275.png">
<meta property="og:updated_time" content="2019-07-27T06:07:47.719Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读">
<meta name="twitter:description" content="概要 前面一节，通过简单配置即可实现SpringSecurity表单认证功能，而今天这一节将通过阅读源码的形式来学习SpringSecurity是如何实现这些功能, 前方高能预警，本篇分析源码篇幅较长。">
<meta name="twitter:image" content="https://i.loli.net/2019/05/24/5ce7b959b91be68275.png">



  <link rel="alternate" href="/atom.xml" title="yukong's blog" type="application/atom+xml">




  <link rel="canonical" href="http://www.yukonga.cn/2019/04/12/【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读 | yukong's blog</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?45b7a3cfe46b3fa2c5d46f59f590664e";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">yukong's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">learning program</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.yukonga.cn/2019/04/12/【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yukong">
      <meta itemprop="description" content="你若对得起时间，时间便对得起你">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="yukong's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-04-12 15:58:25" itemprop="dateCreated datePublished" datetime="2019-04-12T15:58:25+08:00">2019-04-12</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-07-27 14:07:47" itemprop="dateModified" datetime="2019-07-27T14:07:47+08:00">2019-07-27</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/SpringSecurity/" itemprop="url" rel="index"><span itemprop="name">SpringSecurity</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/2019/04/12/【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/04/12/【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
            <span id="/2019/04/12/【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读/" class="leancloud_visitors" data-flag-title="【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="概要"><a class="markdownIt-Anchor" href="#概要"></a> 概要</h2>
<p>前面一节，通过简单配置即可实现SpringSecurity表单认证功能，而今天这一节将通过阅读源码的形式来学习SpringSecurity是如何实现这些功能, 前方高能预警，<strong><code>本篇分析源码篇幅较长</code></strong>。</p>
<a id="more"></a>
<h2 id="过滤器链"><a class="markdownIt-Anchor" href="#过滤器链"></a> 过滤器链</h2>
<p>前面我说过SpringSecurity是基于过滤器链的形式，那么我解析将会介绍一下具体有哪些过滤器。</p>
<table>
<thead>
<tr>
<th style="text-align:center">Filter Class</th>
<th style="text-align:center">介绍</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">SecurityContextPersistenceFilter</td>
<td style="text-align:center">判断当前用户是否登录</td>
</tr>
<tr>
<td style="text-align:center">CrsfFilter</td>
<td style="text-align:center">用于防止csrf攻击</td>
</tr>
<tr>
<td style="text-align:center">LogoutFilter</td>
<td style="text-align:center">处理注销请求</td>
</tr>
<tr>
<td style="text-align:center">UsernamePasswordAuthenticationFilter</td>
<td style="text-align:center">处理表单登录的请求(也是我们今天的主角)</td>
</tr>
<tr>
<td style="text-align:center">BasicAuthenticationFilter</td>
<td style="text-align:center">处理http basic认证的请求</td>
</tr>
</tbody>
</table>
<p>由于过滤器链中的过滤器实在太多，我没有一一列举，调了几个比较重要的介绍一下。</p>
<p>通过上面我们知道SpringSecurity对于表单登录的认证请求是交给了UsernamePasswordAuthenticationFilter处理的，那么具体的认证流程如下：</p>
<p><img src="https://i.loli.net/2019/05/24/5ce7b959b91be68275.png" alt="">从上图可知，<code>UsernamePasswordAuthenticationFilter</code>继承于抽象类<code>AbstractAuthenticationProcessingFilter</code>。</p>
<p>具体认证是：</p>
<ol>
<li>进入doFilter方法，判断是否要认证，如果需要认证则进入attemptAuthentication方法，如果不需要直接结束</li>
<li>attemptAuthentication方法中根据username跟password构造一个UsernamePasswordAuthenticationToken对象(此时的token是未认证的)，并且将它交给ProviderManger来完成认证。</li>
<li>ProviderManger中维护这一个AuthenticationProvider对象列表，通过遍历判断并且最后选择DaoAuthenticationProvider对象来完成最后的认证。</li>
<li>DaoAuthenticationProvider根据ProviderManger传来的token取出username，并且调用我们写的UserDetailsService的loadUserByUsername方法从数据库中读取用户信息，然后对比用户密码，如果认证通过，则返回用户信息也是就是UserDetails对象，在重新构造UsernamePasswordAuthenticationToken(此时的token是 已经认证通过了的)。</li>
</ol>
<p>接下来我们将通过源码来分析具体的整个认证流程。</p>
<h2 id="abstractauthenticationprocessingfilter"><a class="markdownIt-Anchor" href="#abstractauthenticationprocessingfilter"></a> AbstractAuthenticationProcessingFilter</h2>
<p>AbstractAuthenticationProcessingFilter 是一个抽象类。所有的认证认证请求的过滤器都会继承于它，它主要将一些公共的功能实现，而具体的验证逻辑交给子类实现，有点类似于父类设置好认证流程，子类负责具体的认证逻辑，这样跟设计模式的<strong>模板方法模式</strong>有点相似。</p>
<p>现在我们分析一下 它里面比较重要的方法</p>
<h3 id="1-dofilter"><a class="markdownIt-Anchor" href="#1-dofilter"></a> 1、doFilter</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doFilter</span><span class="params">(ServletRequest req, ServletResponse res, FilterChain chain)</span></span></span><br><span class="line"><span class="function">			<span class="keyword">throws</span> IOException, ServletException </span>&#123;</span><br><span class="line">		<span class="comment">// 省略不相干代码。。。</span></span><br><span class="line">    <span class="comment">// 1、判断当前请求是否要认证</span></span><br><span class="line">		<span class="keyword">if</span> (!requiresAuthentication(request, response)) &#123;</span><br><span class="line">      <span class="comment">// 不需要直接走下一个过滤器</span></span><br><span class="line">			chain.doFilter(request, response);</span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">// 2、开始请求认证，attemptAuthentication具体实现给子类，如果认证成功返回一个认证通过的Authenticaion对象</span></span><br><span class="line">			authResult = attemptAuthentication(request, response);</span><br><span class="line">			<span class="keyword">if</span> (authResult == <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">return</span>;</span><br><span class="line">			&#125;</span><br><span class="line">      <span class="comment">// 3、登录成功 将认证成功的用户信息放入session SessionAuthenticationStrategy接口，用于扩展</span></span><br><span class="line">			sessionStrategy.onAuthentication(authResult, request, response);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">catch</span> (InternalAuthenticationServiceException failed) &#123;</span><br><span class="line">      <span class="comment">//2.1、发生异常，登录失败，进入登录失败handler回调</span></span><br><span class="line">			unsuccessfulAuthentication(request, response, failed);</span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">catch</span> (AuthenticationException failed) &#123;</span><br><span class="line">      <span class="comment">//2.1、发生异常，登录失败，进入登录失败处理器</span></span><br><span class="line">			unsuccessfulAuthentication(request, response, failed);</span><br><span class="line">			<span class="keyword">return</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">// 3.1、登录成功，进入登录成功处理器。</span></span><br><span class="line">		successfulAuthentication(request, response, chain, authResult);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-successfulauthentication"><a class="markdownIt-Anchor" href="#2-successfulauthentication"></a> 2、successfulAuthentication</h3>
<p>登录成功处理器</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">successfulAuthentication</span><span class="params">(HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">			HttpServletResponse response, FilterChain chain, Authentication authResult)</span></span></span><br><span class="line"><span class="function">			<span class="keyword">throws</span> IOException, ServletException </span>&#123;</span><br><span class="line">    <span class="comment">//1、登录成功 将认证成功的Authentication对象存入SecurityContextHolder中</span></span><br><span class="line">    <span class="comment">// 	 SecurityContextHolder本质是一个ThreadLocal</span></span><br><span class="line">		SecurityContextHolder.getContext().setAuthentication(authResult);</span><br><span class="line">    <span class="comment">//2、如果开启了记住我功能，将调用rememberMeServices的loginSuccess 将生成一个token</span></span><br><span class="line">  	<span class="comment">//   将token放入cookie中这样 下次就不用登录就可以认证。具体关于记住我rememberMeServices的相关分析我					们下面几篇文章会深入分析的。</span></span><br><span class="line">		rememberMeServices.loginSuccess(request, response, authResult);</span><br><span class="line">		<span class="comment">// Fire event</span></span><br><span class="line">    <span class="comment">//3、发布一个登录事件。</span></span><br><span class="line">		<span class="keyword">if</span> (<span class="keyword">this</span>.eventPublisher != <span class="keyword">null</span>) &#123;</span><br><span class="line">			eventPublisher.publishEvent(<span class="keyword">new</span> InteractiveAuthenticationSuccessEvent(</span><br><span class="line">					authResult, <span class="keyword">this</span>.getClass()));</span><br><span class="line">		&#125;</span><br><span class="line">    <span class="comment">//4、调用我们自己定义的登录成功处理器，这样也是我们扩展得知登录成功的一个扩展点。</span></span><br><span class="line">		successHandler.onAuthenticationSuccess(request, response, authResult);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<h3 id="3-unsuccessfulauthentication"><a class="markdownIt-Anchor" href="#3-unsuccessfulauthentication"></a> 3、unsuccessfulAuthentication</h3>
<p>登录失败处理器</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">unsuccessfulAuthentication</span><span class="params">(HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">			HttpServletResponse response, AuthenticationException failed)</span></span></span><br><span class="line"><span class="function">			<span class="keyword">throws</span> IOException, ServletException </span>&#123;</span><br><span class="line">    <span class="comment">//1、登录失败，将SecurityContextHolder中的信息清空</span></span><br><span class="line">		SecurityContextHolder.clearContext();</span><br><span class="line">    <span class="comment">//2、关于记住我功能的登录失败处理</span></span><br><span class="line">		rememberMeServices.loginFail(request, response);</span><br><span class="line">    <span class="comment">//3、调用我们自己定义的登录失败处理器，这里可以扩展记录登录失败的日志。</span></span><br><span class="line">		failureHandler.onAuthenticationFailure(request, response, failed);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<p>关于AbstractAuthenticationProcessingFilter主要分析就到这。我们可以从源码中知道，当请求进入该过滤器中具体的流程是</p>
<ol>
<li>判断该请求是否要被认证</li>
<li>调用<code>attemptAuthentication</code>方法开始认证，由于是抽象方法具体认证逻辑给子类</li>
<li>如果登录成功，则将认证结果<code>Authentication</code>对象根据session策略写入session中，将认证结果写入到<code>SecurityContextHolder</code>,如果开启了记住我功能，则根据记住我功能，生成token并且写入cookie中，最后调用一个<code>successHandler</code>对象的方法，这个对象可以是我们配置注入的，用于处理我们的自定义登录成功的一些逻辑（比如记录登录成功日志等等）。</li>
<li>如果登录失败，则清空<code>SecurityContextHolder</code>中的信息，并且调用我们自己注入的<code>failureHandler</code>对象，处理我们自己的登录失败逻辑。</li>
</ol>
<h2 id="usernamepasswordauthenticationfilter"><a class="markdownIt-Anchor" href="#usernamepasswordauthenticationfilter"></a> UsernamePasswordAuthenticationFilter</h2>
<p>从上面分析我们可以知道，<code>UsernamePasswordAuthenticationFilter</code>是继承于<code>AbstractAuthenticationProcessingFilter</code>，并且实现它的<code>attemptAuthentication</code>方法，来实现认证具体的逻辑实现。接下来，我们通过阅读<code>UsernamePasswordAuthenticationFilter</code>的源码来解读，它是如何完成认证的。 由于这里会涉及<code>UsernamePasswordAuthenticationToken</code>对象构造，所以我们先看看<code>UsernamePasswordAuthenticationToken</code>的源码</p>
<h3 id="1-usernamepasswordauthenticationtoken"><a class="markdownIt-Anchor" href="#1-usernamepasswordauthenticationtoken"></a> 1、UsernamePasswordAuthenticationToken</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 继承至AbstractAuthenticationToken </span></span><br><span class="line"><span class="comment">// AbstractAuthenticationToken主要定义一下在SpringSecurity中toke需要存在一些必须信息</span></span><br><span class="line"><span class="comment">// 例如权限集合  Collection&lt;GrantedAuthority&gt; authorities; 是否认证通过boolean authenticated = false;认证通过的用户信息Object details;</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UsernamePasswordAuthenticationToken</span> <span class="keyword">extends</span> <span class="title">AbstractAuthenticationToken</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line">  <span class="comment">// 未登录情况下 存的是用户名 登录成功情况下存的是UserDetails对象</span></span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">final</span> Object principal;</span><br><span class="line">  <span class="comment">// 密码</span></span><br><span class="line">	<span class="keyword">private</span> Object credentials;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 构造函数，用户没有登录的情况下，此时的authenticated是false，代表尚未认证</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">UsernamePasswordAuthenticationToken</span><span class="params">(Object principal, Object credentials)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">super</span>(<span class="keyword">null</span>);</span><br><span class="line">		<span class="keyword">this</span>.principal = principal;</span><br><span class="line">		<span class="keyword">this</span>.credentials = credentials;</span><br><span class="line">		setAuthenticated(<span class="keyword">false</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 构造函数，用户登录成功的情况下，多了一个参数 是用户的权限集合，此时的authenticated是true，代表认证成功</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="title">UsernamePasswordAuthenticationToken</span><span class="params">(Object principal, Object credentials,</span></span></span><br><span class="line"><span class="function"><span class="params">			Collection&lt;? extends GrantedAuthority&gt; authorities)</span> </span>&#123;</span><br><span class="line">		<span class="keyword">super</span>(authorities);</span><br><span class="line">		<span class="keyword">this</span>.principal = principal;</span><br><span class="line">		<span class="keyword">this</span>.credentials = credentials;</span><br><span class="line">		<span class="keyword">super</span>.setAuthenticated(<span class="keyword">true</span>); <span class="comment">// must use super, as we override</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>接下来我们就可以分析attemptAuthentication方法了。</p>
<h3 id="2-attemptauthentication"><a class="markdownIt-Anchor" href="#2-attemptauthentication"></a> 2、attemptAuthentication</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Authentication <span class="title">attemptAuthentication</span><span class="params">(HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">			HttpServletResponse response)</span> <span class="keyword">throws</span> AuthenticationException </span>&#123;</span><br><span class="line">     <span class="comment">// 1、判断是不是post请求，如果不是则抛出AuthenticationServiceException异常，注意这里抛出的异常都在AbstractAuthenticationProcessingFilter#doFilter方法中捕获，捕获之后会进入登录失败的逻辑。</span></span><br><span class="line">		<span class="keyword">if</span> (postOnly &amp;&amp; !request.getMethod().equals(<span class="string">"POST"</span>)) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> AuthenticationServiceException(</span><br><span class="line">					<span class="string">"Authentication method not supported: "</span> + request.getMethod());</span><br><span class="line">		&#125;</span><br><span class="line">    <span class="comment">// 2、从request中拿用户名跟密码</span></span><br><span class="line">		String username = obtainUsername(request);</span><br><span class="line">		String password = obtainPassword(request);</span><br><span class="line">		<span class="comment">// 3、非空处理，防止NPE异常</span></span><br><span class="line">		<span class="keyword">if</span> (username == <span class="keyword">null</span>) &#123;</span><br><span class="line">			username = <span class="string">""</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">if</span> (password == <span class="keyword">null</span>) &#123;</span><br><span class="line">			password = <span class="string">""</span>;</span><br><span class="line">		&#125;</span><br><span class="line">    <span class="comment">// 4、除去空格</span></span><br><span class="line">		username = username.trim();</span><br><span class="line">    <span class="comment">// 5、根据username跟password构造出一个UsernamePasswordAuthenticationToken对象 从上文分析可知道，此时的token是未认证的。</span></span><br><span class="line">		UsernamePasswordAuthenticationToken authRequest = <span class="keyword">new</span> UsernamePasswordAuthenticationToken(</span><br><span class="line">				username, password);</span><br><span class="line">    <span class="comment">// 6、配置一下其他信息 ip 等等</span></span><br><span class="line">		setDetails(request, authRequest);</span><br><span class="line">   <span class="comment">//  7、调用ProviderManger的authenticate的方法进行具体认证逻辑</span></span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">this</span>.getAuthenticationManager().authenticate(authRequest);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<h2 id="providermanager"><a class="markdownIt-Anchor" href="#providermanager"></a> ProviderManager</h2>
<p>维护一个AuthenticationProvider列表，进行认证逻辑验证</p>
<h3 id="1-authenticate"><a class="markdownIt-Anchor" href="#1-authenticate"></a> 1、authenticate</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Authentication <span class="title">authenticate</span><span class="params">(Authentication authentication)</span></span></span><br><span class="line"><span class="function">			<span class="keyword">throws</span> AuthenticationException </span>&#123;</span><br><span class="line">    <span class="comment">// 1、拿到token的类型。</span></span><br><span class="line">		Class&lt;? extends Authentication&gt; toTest = authentication.getClass();</span><br><span class="line">		AuthenticationException lastException = <span class="keyword">null</span>;</span><br><span class="line">		Authentication result = <span class="keyword">null</span>;</span><br><span class="line">   <span class="comment">// 2、遍历AuthenticationProvider列表</span></span><br><span class="line">		<span class="keyword">for</span> (AuthenticationProvider provider : getProviders()) &#123;</span><br><span class="line">      <span class="comment">// 3、AuthenticationProvider不支持当前token类型，则直接跳过</span></span><br><span class="line">			<span class="keyword">if</span> (!provider.supports(toTest)) &#123;</span><br><span class="line">				<span class="keyword">continue</span>;</span><br><span class="line">			&#125;</span><br><span class="line"></span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 4、如果Provider支持当前token，则交给Provider完成认证。</span></span><br><span class="line">				result = provider.authenticate(authentication);</span><br><span class="line">     </span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">catch</span> (AccountStatusException e) &#123;</span><br><span class="line"></span><br><span class="line">				<span class="keyword">throw</span> e;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">catch</span> (InternalAuthenticationServiceException e) &#123;</span><br><span class="line">				<span class="keyword">throw</span> e;</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">catch</span> (AuthenticationException e) &#123;</span><br><span class="line">				lastException = e;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">    <span class="comment">// 5、登录成功 返回登录成功的token</span></span><br><span class="line">		<span class="keyword">if</span> (result != <span class="keyword">null</span>) &#123;</span><br><span class="line">			eventPublisher.publishAuthenticationSuccess(result);</span><br><span class="line">			<span class="keyword">return</span> result;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<h2 id="abstractuserdetailsauthenticationprovider"><a class="markdownIt-Anchor" href="#abstractuserdetailsauthenticationprovider"></a> AbstractUserDetailsAuthenticationProvider</h2>
<h3 id="1-authenticate-2"><a class="markdownIt-Anchor" href="#1-authenticate-2"></a> 1、authenticate</h3>
<p><code>AbstractUserDetailsAuthenticationProvider</code>实现了<code>AuthenticationProvider</code>接口，并且实现了部分方法，<code>DaoAuthenticationProvider</code>继承于<code>AbstractUserDetailsAuthenticationProvider</code>类，所以我们先来看看<code>AbstractUserDetailsAuthenticationProvider</code>的实现。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">AbstractUserDetailsAuthenticationProvider</span> <span class="keyword">implements</span></span></span><br><span class="line"><span class="class">		<span class="title">AuthenticationProvider</span>, <span class="title">InitializingBean</span>, <span class="title">MessageSourceAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 国际化处理</span></span><br><span class="line">	<span class="keyword">protected</span> MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 对token一些检查，具体检查逻辑交给子类实现，抽象方法</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">additionalAuthenticationChecks</span><span class="params">(UserDetails userDetails,</span></span></span><br><span class="line"><span class="function"><span class="params">			UsernamePasswordAuthenticationToken authentication)</span></span></span><br><span class="line"><span class="function">			<span class="keyword">throws</span> AuthenticationException</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * 认证逻辑的实现，调用抽象方法retrieveUser根据username获取UserDetails对象</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> Authentication <span class="title">authenticate</span><span class="params">(Authentication authentication)</span></span></span><br><span class="line"><span class="function">			<span class="keyword">throws</span> AuthenticationException </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 1、获取usernmae</span></span><br><span class="line">		String username = (authentication.getPrincipal() == <span class="keyword">null</span>) ? <span class="string">"NONE_PROVIDED"</span></span><br><span class="line">				: authentication.getName();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2、尝试去缓存中获取UserDetails对象</span></span><br><span class="line">		UserDetails user = <span class="keyword">this</span>.userCache.getUserFromCache(username);</span><br><span class="line">    <span class="comment">// 3、如果为空，则代表当前对象没有缓存。</span></span><br><span class="line">		<span class="keyword">if</span> (user == <span class="keyword">null</span>) &#123;</span><br><span class="line">			cacheWasUsed = <span class="keyword">false</span>;</span><br><span class="line">			<span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">//4、调用retrieveUser去获取UserDetail对象，为什么这个方法是抽象方法大家很容易知道，如果UserDetail信息存在关系数据库 则可以重写该方法并且去关系数据库获取用户信息，如果UserDetail信息存在其他地方，可以重写该方法用其他的方法去获取用户信息，这样丝毫不影响整个认证流程，方便扩展。</span></span><br><span class="line">				user = retrieveUser(username,</span><br><span class="line">						(UsernamePasswordAuthenticationToken) authentication);</span><br><span class="line">			&#125;</span><br><span class="line">      <span class="keyword">catch</span> (UsernameNotFoundException notFound) &#123;</span><br><span class="line">				</span><br><span class="line">				<span class="comment">// 捕获异常 日志处理 并且往上抛出，登录失败。</span></span><br><span class="line">				<span class="keyword">if</span> (hideUserNotFoundExceptions) &#123;</span><br><span class="line">					<span class="keyword">throw</span> <span class="keyword">new</span> BadCredentialsException(messages.getMessage(</span><br><span class="line">							<span class="string">"AbstractUserDetailsAuthenticationProvider.badCredentials"</span>,</span><br><span class="line">							<span class="string">"Bad credentials"</span>));</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">else</span> &#123;</span><br><span class="line">					<span class="keyword">throw</span> notFound;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">// 5、前置检查  判断当前用户是否锁定，禁用等等</span></span><br><span class="line">			preAuthenticationChecks.check(user);</span><br><span class="line">      <span class="comment">// 6、其他的检查，在DaoAuthenticationProvider是检查密码是否一致</span></span><br><span class="line">			additionalAuthenticationChecks(user,</span><br><span class="line">					(UsernamePasswordAuthenticationToken) authentication);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">catch</span> (AuthenticationException exception) &#123;</span><br><span class="line">		</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 7、后置检查，判断密码是否过期</span></span><br><span class="line">		postAuthenticationChecks.check(user);</span><br><span class="line"></span><br><span class="line">	 </span><br><span class="line">		<span class="comment">// 8、登录成功通过UserDetail对象重新构造一个认证通过的Token对象</span></span><br><span class="line">		<span class="keyword">return</span> createSuccessAuthentication(principalToReturn, authentication, user);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	</span><br><span class="line">	<span class="function"><span class="keyword">protected</span> Authentication <span class="title">createSuccessAuthentication</span><span class="params">(Object principal,</span></span></span><br><span class="line"><span class="function"><span class="params">			Authentication authentication, UserDetails user)</span> </span>&#123;</span><br><span class="line">		<span class="comment">// 调用第二个构造方法，构造一个认证通过的Token对象</span></span><br><span class="line">		UsernamePasswordAuthenticationToken result = <span class="keyword">new</span> UsernamePasswordAuthenticationToken(</span><br><span class="line">				principal, authentication.getCredentials(),</span><br><span class="line">				authoritiesMapper.mapAuthorities(user.getAuthorities()));</span><br><span class="line">		result.setDetails(authentication.getDetails());</span><br><span class="line"></span><br><span class="line">		<span class="keyword">return</span> result;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>接下来我们具体看看<code>retrieveUser</code>的实现，没看源码大家应该也可以知道，<code>retrieveUser</code>方法应该是调用<code>UserDetailsService</code>去数据库查询是否有该用户，以及用户的密码是否一致。</p>
<h2 id="daoauthenticationprovider"><a class="markdownIt-Anchor" href="#daoauthenticationprovider"></a> DaoAuthenticationProvider</h2>
<p>DaoAuthenticationProvider 主要是通过UserDetailService来获取UserDetail对象。</p>
<h3 id="1-retrieveuser"><a class="markdownIt-Anchor" href="#1-retrieveuser"></a> 1、retrieveUser</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">final</span> UserDetails <span class="title">retrieveUser</span><span class="params">(String username,</span></span></span><br><span class="line"><span class="function"><span class="params">			UsernamePasswordAuthenticationToken authentication)</span></span></span><br><span class="line"><span class="function">			<span class="keyword">throws</span> AuthenticationException </span>&#123;</span><br><span class="line">		<span class="keyword">try</span> &#123;</span><br><span class="line">      <span class="comment">// 1、调用UserDetailsService接口的loadUserByUsername方法获取UserDeail对象</span></span><br><span class="line">			UserDetails loadedUser = <span class="keyword">this</span>.getUserDetailsService().loadUserByUsername(username);</span><br><span class="line">       <span class="comment">// 2、如果loadedUser为null 代表当前用户不存在，抛出异常 登录失败。</span></span><br><span class="line">			<span class="keyword">if</span> (loadedUser == <span class="keyword">null</span>) &#123;</span><br><span class="line">				<span class="keyword">throw</span> <span class="keyword">new</span> InternalAuthenticationServiceException(</span><br><span class="line">						<span class="string">"UserDetailsService returned null, which is an interface contract violation"</span>);</span><br><span class="line">			&#125;</span><br><span class="line">      <span class="comment">// 3、返回查询的结果</span></span><br><span class="line">			<span class="keyword">return</span> loadedUser;</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-additionalauthenticationchecks"><a class="markdownIt-Anchor" href="#2-additionalauthenticationchecks"></a> 2、additionalAuthenticationChecks</h3>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">additionalAuthenticationChecks</span><span class="params">(UserDetails userDetails,</span></span></span><br><span class="line"><span class="function"><span class="params">			UsernamePasswordAuthenticationToken authentication)</span></span></span><br><span class="line"><span class="function">			<span class="keyword">throws</span> AuthenticationException </span>&#123;</span><br><span class="line">    <span class="comment">// 1、如果密码为空，则抛出异常、</span></span><br><span class="line">		<span class="keyword">if</span> (authentication.getCredentials() == <span class="keyword">null</span>) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> BadCredentialsException(messages.getMessage(</span><br><span class="line">					<span class="string">"AbstractUserDetailsAuthenticationProvider.badCredentials"</span>,</span><br><span class="line">					<span class="string">"Bad credentials"</span>));</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2、获取用户输入的密码</span></span><br><span class="line">		String presentedPassword = authentication.getCredentials().toString();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3、调用passwordEncoder的matche方法 判断密码是否一致</span></span><br><span class="line">		<span class="keyword">if</span> (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) &#123;</span><br><span class="line">			logger.debug(<span class="string">"Authentication failed: password does not match stored value"</span>);</span><br><span class="line"></span><br><span class="line">      <span class="comment">// 4、如果不一致 则抛出异常。</span></span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> BadCredentialsException(messages.getMessage(</span><br><span class="line">					<span class="string">"AbstractUserDetailsAuthenticationProvider.badCredentials"</span>,</span><br><span class="line">					<span class="string">"Bad credentials"</span>));</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<h2 id="总结"><a class="markdownIt-Anchor" href="#总结"></a> 总结</h2>
<p>至此，整认证流程已经分析完毕，大家如果有什么不懂可以关注我的公众号一起讨论。</p>
<p>学习是一个漫长的过程，学习源码可能会很困难但是只要努力一定就会有获取，大家一致共勉。</p>
<p><img src="https://i.loli.net/2019/05/24/5ce7b959b91be68275.png" alt=""></p>

      
    </div>

    

    
    
    

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>喜欢就请博主喝个☕️吧</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="yukong 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="yukong 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>yukong</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="http://www.yukonga.cn/2019/04/12/【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读/" title="【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读">http://www.yukonga.cn/2019/04/12/【SpringSecurity系列02】SpringSecurity UsernamePasswordAuthenticationFilter认证逻辑源码解读/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    
    

      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/SpringBoot/" rel="tag"><i class="fa fa-tag"></i> SpringBoot</a>
          
            <a href="/tags/SpringSecurity/" rel="tag"><i class="fa fa-tag"></i> SpringSecurity</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/04/11/【SpringSecurity系列01】初识SpringSecurity/" rel="next" title="【SpringSecurity系列01】初识SpringSecurity">
                <i class="fa fa-chevron-left"></i> 【SpringSecurity系列01】初识SpringSecurity
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/05/27/LeetCode-338-Counting-Bits/" rel="prev" title="LeetCode-338 Counting Bits">
                LeetCode-338 Counting Bits <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.png" alt="yukong">
            
              <p class="site-author-name" itemprop="name">yukong</p>
              <div class="site-description motion-element" itemprop="description">你若对得起时间，时间便对得起你</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">26</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">6</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/YuKongEr" title="GitHub &rarr; https://github.com/YuKongEr" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:yukongcode@gmail.com" title="E-Mail &rarr; mailto:yukongcode@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.jianshu.com/u/bc2e35b66293" title="简书 &rarr; https://www.jianshu.com/u/bc2e35b66293" rel="noopener" target="_blank"><i class="fa fa-fw fa-skype"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://blog.csdn.net/xp541130126" title="csdn &rarr; https://blog.csdn.net/xp541130126" rel="noopener" target="_blank"><i class="fa fa-fw fa-vk"></i>csdn</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#概要"><span class="nav-number">1.</span> <span class="nav-text"> 概要</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#过滤器链"><span class="nav-number">2.</span> <span class="nav-text"> 过滤器链</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#abstractauthenticationprocessingfilter"><span class="nav-number">3.</span> <span class="nav-text"> AbstractAuthenticationProcessingFilter</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-dofilter"><span class="nav-number">3.1.</span> <span class="nav-text"> 1、doFilter</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-successfulauthentication"><span class="nav-number">3.2.</span> <span class="nav-text"> 2、successfulAuthentication</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-unsuccessfulauthentication"><span class="nav-number">3.3.</span> <span class="nav-text"> 3、unsuccessfulAuthentication</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#usernamepasswordauthenticationfilter"><span class="nav-number">4.</span> <span class="nav-text"> UsernamePasswordAuthenticationFilter</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-usernamepasswordauthenticationtoken"><span class="nav-number">4.1.</span> <span class="nav-text"> 1、UsernamePasswordAuthenticationToken</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-attemptauthentication"><span class="nav-number">4.2.</span> <span class="nav-text"> 2、attemptAuthentication</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#providermanager"><span class="nav-number">5.</span> <span class="nav-text"> ProviderManager</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-authenticate"><span class="nav-number">5.1.</span> <span class="nav-text"> 1、authenticate</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#abstractuserdetailsauthenticationprovider"><span class="nav-number">6.</span> <span class="nav-text"> AbstractUserDetailsAuthenticationProvider</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-authenticate-2"><span class="nav-number">6.1.</span> <span class="nav-text"> 1、authenticate</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#daoauthenticationprovider"><span class="nav-number">7.</span> <span class="nav-text"> DaoAuthenticationProvider</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-retrieveuser"><span class="nav-number">7.1.</span> <span class="nav-text"> 1、retrieveUser</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-additionalauthenticationchecks"><span class="nav-number">7.2.</span> <span class="nav-text"> 2、additionalAuthenticationChecks</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">8.</span> <span class="nav-text"> 总结</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yukong</span>

  

  
</div>
<div class="BbeiAn-info">
浙ICP备 -
<a target="_blank" href="http://www.miitbeian.gov.cn">19015067号</a>

</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="post-meta-item-icon">
      <i class="fa fa-user"></i>
      您是访问本站的第&nbsp
    </span>
    <span class="site-uv" title="总访客量">
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      &nbsp 位朋友
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="post-meta-item-icon">
      <i class="fa fa-eye"></i>
      本站总共访问&nbsp
    </span>
    <span class="site-pv" title="总访问量">
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>









        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.1"></script>

  <script src="/js/src/motion.js?v=7.0.1"></script>



  
  


  <script src="/js/src/affix.js?v=7.0.1"></script>

  <script src="/js/src/schemes/pisces.js?v=7.0.1"></script>




  
  <script src="/js/src/scrollspy.js?v=7.0.1"></script>
<script src="/js/src/post-details.js?v=7.0.1"></script>



  


  <script src="/js/src/next-boot.js?v=7.0.1"></script>


  

  

  

  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
    appKey: 'n3ohmj1CGAM1GUfp6SqF4LXh',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: 'zh-cn' || 'zh-cn'
  });
</script>




  


  




  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
                'X-LC-Key': 'n3ohmj1CGAM1GUfp6SqF4LXh',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  

  

  

  

  

  

  

  

  

  
<script>
  $('.highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
